package com.ztesoft.book.admin.handler;

import com.ztesoft.book.common.utils.Result;
import com.ztesoft.book.common.utils.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description: 统一异常处理类
 * @Author: YangFan
 * @Date: 2021-03-18 16:59
 */
@Slf4j
@RestControllerAdvice
public class UnionExceptionHandler {

    @ExceptionHandler(ServiceException.class)
    public Result handleServiceException(ServiceException e) {
        Result r = new Result();
        r.put("code", e.getCode());
        r.put("msg", e.getMessage());
        return r;
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public Result handlerNoFoundException(Exception e) {
        log.error("NoHandlerFoundException", e);
        return Result.error(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("DuplicateKeyException", e);
        return Result.error("数据库中已存在该记录");
    }

    @ExceptionHandler(UnauthorizedException.class)
    public Result handleAuthorizationException(UnauthorizedException e, HttpServletResponse response) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        // 记录日志
        log.error("UnauthorizedException:非法会话", e);
        return Result.error(HttpStatus.UNAUTHORIZED.value(), "没有权限，请联系管理员授权");
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result handleHttpRequestMethodNotSupportedException(UnauthorizedException e, HttpServletResponse response) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setStatus(HttpStatus.METHOD_NOT_ALLOWED.value());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        // 记录日志
        log.error("MethodNotSupportedException:请求不支持", e);
        return Result.error(HttpStatus.METHOD_NOT_ALLOWED.value(), "不支持当前的请求方式");
    }


    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        log.error("Exception", e);
        return Result.error();
    }

    /**
     * 参数检验异常
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = ConstraintViolationException.class)
    public Result constraintViolationExceptionHandler(ConstraintViolationException ex) {
        Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
        Iterator<ConstraintViolation<?>> iterator = constraintViolations.iterator();
        List<String> msgList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConstraintViolation<?> cvl = iterator.next();
            msgList.add(cvl.getMessageTemplate());
        }
        return Result.error(msgList.stream().collect(Collectors.joining(", ")));
    }

    /**
     * 参数检验异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidHandler(MethodArgumentNotValidException e) {
        List<String> msgList = new ArrayList<>();
        for (FieldError error : e.getBindingResult().getFieldErrors()) {
            msgList.add(error.getDefaultMessage());
        }
        return Result.error(msgList.stream().collect(Collectors.joining(", ")));
    }
}
